package org.itboys.manager;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.itboys.product.entity.Product;
import org.itboys.product.entity.ProductCategory;
import org.itboys.product.service.ProductCategoryService;
import org.itboys.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * Created by huml on 2016/4/15.
 * 微网上面的产品业务
 */
@Service
public class ProductWeixinService {
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private ProductService productService;

    /**
     * 微信商城的首页产品数据
     * @param sellerId
     * @return
     */
    public List<ProductCategory> productIndexData(Long sellerId){
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
        param.put("sellerId", sellerId);
        param.put("orderByKey", "sort");
        List<ProductCategory> categories = productCategoryService.list(param);
        List<Long> catIds = Lists.newArrayListWithExpectedSize(categories.size()+1);
        catIds.add(0L);
        for (ProductCategory category : categories) {
            catIds.add(category.getId());
        }
        param.clear();
        param.put("categoryId in", catIds);
        List<Product> products = productService.list(param);
        for (ProductCategory category : categories) {
            List<Product> childProducts = Lists.newArrayList();
            for (Product product : products) {
                if(product.getCategoryId().equals(Long.valueOf(category.getId()))){
                    BigDecimal price = new BigDecimal(product.getPrice());
                    price = price.divide(new BigDecimal(100));
                    product.setPrice(price.intValue());
                    childProducts.add(product);
                }
            }
            category.setProducts(childProducts);
        }
        return categories;
    }

}
